<template>
  <div class="color-assignment-test">
    <h2>🎨 颜色分配测试</h2>
    
    <div class="test-info">
      <p>这个页面用于测试自动颜色分配功能。每个玩家加入房间时会自动获得不同的颜色。</p>
    </div>
    
    <div class="controls">
      <el-button @click="connect" :disabled="isConnected" type="primary">
        连接服务器
      </el-button>
      <el-button @click="disconnect" :disabled="!isConnected" type="danger">
        断开连接
      </el-button>
      <el-button @click="createRoom" :disabled="!isConnected" type="success">
        创建房间
      </el-button>
      <el-button @click="joinRoom" :disabled="!isConnected" type="warning">
        加入房间
      </el-button>
      <el-button @click="leaveRoom" :disabled="!isConnected" type="info">
        离开房间
      </el-button>
    </div>
    
    <div class="room-info" v-if="roomId">
      <h3>🏠 房间信息</h3>
      <div class="info-grid">
        <div class="info-item">
          <label>房间ID:</label>
          <span>{{ roomId }}</span>
        </div>
        <div class="info-item">
          <label>当前玩家:</label>
          <span>{{ currentPlayer?.nickname }}</span>
        </div>
        <div class="info-item">
          <label>分配颜色:</label>
          <div class="color-preview" :style="{ backgroundColor: currentPlayer?.color }">
            {{ currentPlayer?.color || '等待分配...' }}
          </div>
        </div>
        <div class="info-item">
          <label>玩家数量:</label>
          <span>{{ players.length }}</span>
        </div>
      </div>
    </div>
    
    <div class="players-section">
      <h3>👥 玩家列表</h3>
      <div class="players-grid">
        <div
          v-for="player in players"
          :key="player.id"
          class="player-card"
          :class="{ 'current-player': player.id === currentPlayer?.id }"
        >
          <div class="player-avatar">
            <div 
              class="avatar-color" 
              :style="{ backgroundColor: player.color }"
            ></div>
            <div v-if="player.isOwner" class="owner-badge">房主</div>
          </div>
          
          <div class="player-info">
            <div class="player-name">{{ player.nickname }}</div>
            <div class="player-color">
              颜色: <span class="color-code">{{ player.color }}</span>
            </div>
            <div class="player-id">ID: {{ player.id }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="test-instructions">
      <h3>📋 测试步骤</h3>
      <ol>
        <li>点击"连接服务器"按钮</li>
        <li>点击"创建房间"按钮（第一个玩家）</li>
        <li>打开新的浏览器窗口，访问相同页面</li>
        <li>在新窗口中点击"连接服务器"和"加入房间"</li>
        <li>观察每个玩家是否获得不同的颜色</li>
        <li>重复步骤3-5，测试更多玩家</li>
      </ol>
      
      <div class="expected-results">
        <h4>✅ 预期结果</h4>
        <ul>
          <li>每个玩家应该获得不同的颜色</li>
          <li>颜色应该是预定义的15种颜色之一</li>
          <li>玩家离开后，颜色应该被释放</li>
          <li>新玩家加入时应该获得可用颜色</li>
        </ul>
      </div>
    </div>
    
    <div class="log-section">
      <h3>📝 事件日志</h3>
      <div class="log-controls">
        <el-button @click="clearLogs" size="small" type="info">清空日志</el-button>
        <el-button @click="exportLogs" size="small" type="success">导出日志</el-button>
      </div>
      <div class="log-content">
        <div v-for="log in logs.slice(-15)" :key="log.id" class="log-item" :class="log.type">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { createSignalRService } from '@/services/socketService'
import { useGameStore } from '@/stores/game'
import { ElMessage } from 'element-plus'

const gameStore = useGameStore()
const isConnected = ref(false)
const roomId = ref('')
const currentPlayer = ref(null)
const players = ref([])
const logs = ref([])

const signalRService = createSignalRService(gameStore)

function addLog(type, message) {
  logs.value.push({
    id: Date.now() + Math.random(),
    type: type || 'info',
    message,
    time: new Date().toLocaleTimeString()
  })
  if (logs.value.length > 100) logs.value.shift()
}

function clearLogs() {
  logs.value = []
  addLog('info', '日志已清空')
}

function exportLogs() {
  const logText = logs.value.map(log => `[${log.time}] ${log.message}`).join('\n')
  const blob = new Blob([logText], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `color-test-logs-${new Date().toISOString().slice(0, 19)}.txt`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('日志已导出')
}

async function connect() {
  try {
    addLog('info', '正在连接服务器...')
    await signalRService.connect()
    isConnected.value = true
    addLog('success', '✅ 连接成功')
    ElMessage.success('连接成功')
  } catch (error) {
    addLog('error', '❌ 连接失败: ' + error.message)
    ElMessage.error('连接失败: ' + error.message)
  }
}

async function disconnect() {
  try {
    await signalRService.disconnect()
    isConnected.value = false
    addLog('info', '🔌 已断开连接')
    ElMessage.info('已断开连接')
  } catch (error) {
    addLog('error', '❌ 断开失败: ' + error.message)
  }
}

async function createRoom() {
  try {
    const roomCode = 'color-test-' + Math.random().toString(36).substr(2, 6)
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    
    currentPlayer.value = {
      id: playerId,
      nickname: '测试房主',
      color: '',
      isOwner: true
    }
    
    addLog('info', `🏠 正在创建房间: ${roomCode}`)
    
    await signalRService.createRoom(
      roomCode,
      '颜色测试房间',
      6,
      '',
      playerId,
      '测试房主'
    )
    
    roomId.value = roomCode
    addLog('success', `✅ 房间创建成功: ${roomCode}`)
    ElMessage.success(`房间创建成功！房间代码：${roomCode}`)
  } catch (error) {
    addLog('error', '❌ 创建房间失败: ' + error.message)
    ElMessage.error('创建房间失败: ' + error.message)
  }
}

async function joinRoom() {
  try {
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    
    currentPlayer.value = {
      id: playerId,
      nickname: '测试玩家',
      color: '',
      isOwner: false
    }
    
    const targetRoom = roomId.value || 'color-test-room'
    addLog('info', `👤 正在加入房间: ${targetRoom}`)
    
    await signalRService.joinRoom(
      targetRoom,
      playerId,
      '测试玩家'
    )
    
    addLog('success', `✅ 成功加入房间: ${targetRoom}`)
    ElMessage.success('成功加入房间！')
  } catch (error) {
    addLog('error', '❌ 加入房间失败: ' + error.message)
    ElMessage.error('加入房间失败: ' + error.message)
  }
}

async function leaveRoom() {
  try {
    if (currentPlayer.value && roomId.value) {
      addLog('info', '👋 正在离开房间...')
      await signalRService.leaveRoom(roomId.value, currentPlayer.value.id)
      addLog('success', '✅ 已离开房间')
      currentPlayer.value = null
      roomId.value = ''
      ElMessage.info('已离开房间')
    }
  } catch (error) {
    addLog('error', '❌ 离开房间失败: ' + error.message)
  }
}

onMounted(() => {
  // 监听游戏状态变化
  const unsubscribe = gameStore.$subscribe((mutation, state) => {
    if (mutation.type === 'patch') {
      // 更新本地状态
      players.value = state.players
      if (state.currentPlayer) {
        currentPlayer.value = state.currentPlayer
        // 如果颜色发生变化，记录日志
        if (state.currentPlayer.color && state.currentPlayer.color !== currentPlayer.value.color) {
          addLog('success', `🎨 玩家颜色已分配: ${state.currentPlayer.color}`)
        }
      }
    }
  })
  
  // 监听SignalR事件
  signalRService.on('Connected', () => {
    addLog('success', '🔗 SignalR连接成功')
  })
  
  signalRService.on('PlayerJoined', (data) => {
    addLog('success', `👤 玩家加入: ${data.Nickname} (颜色: ${data.Color})`)
  })
  
  signalRService.on('PlayerLeft', (data) => {
    addLog('info', `👋 玩家离开: ${data.PlayerId}`)
  })
  
  signalRService.on('RoomCreated', (data) => {
    addLog('success', `🏠 房间创建成功: ${data.RoomCode}`)
  })
  
  signalRService.on('RoomInfo', (data) => {
    addLog('info', `📋 收到房间信息: ${data.Players?.length || 0} 个玩家`)
  })
  
  addLog('info', '🚀 页面已加载，开始测试颜色分配功能')
  
  onUnmounted(() => {
    unsubscribe()
    signalRService.off('Connected')
    signalRService.off('PlayerJoined')
    signalRService.off('PlayerLeft')
    signalRService.off('RoomCreated')
    signalRService.off('RoomInfo')
  })
})
</script>

<style scoped>
.color-assignment-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-info {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.test-info p {
  margin: 0;
  color: #1890ff;
}

.controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.room-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.room-info h3 {
  margin-top: 0;
  color: #333;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-item label {
  font-weight: bold;
  color: #666;
  font-size: 12px;
}

.color-preview {
  padding: 8px 12px;
  border-radius: 4px;
  color: white;
  font-weight: bold;
  text-align: center;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.players-section {
  margin-bottom: 20px;
}

.players-section h3 {
  color: #333;
  margin-bottom: 15px;
}

.players-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.player-card {
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
}

.player-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.player-card.current-player {
  border-color: #1890ff;
  background: #f0f8ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.player-avatar {
  position: relative;
}

.avatar-color {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 3px solid #ddd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.owner-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ff4d4f;
  color: white;
  font-size: 10px;
  padding: 3px 8px;
  border-radius: 12px;
  font-weight: bold;
}

.player-info {
  flex: 1;
}

.player-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
  color: #333;
}

.player-color {
  font-size: 14px;
  margin-bottom: 3px;
  color: #666;
}

.color-code {
  font-family: monospace;
  font-weight: bold;
  color: #1890ff;
}

.player-id {
  font-size: 11px;
  color: #999;
  font-family: monospace;
}

.test-instructions {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.test-instructions h3 {
  margin-top: 0;
  color: #52c41a;
}

.test-instructions ol {
  margin: 15px 0;
  padding-left: 20px;
}

.test-instructions li {
  margin-bottom: 8px;
  color: #333;
}

.expected-results {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #b7eb8f;
}

.expected-results h4 {
  color: #52c41a;
  margin-bottom: 10px;
}

.expected-results ul {
  margin: 0;
  padding-left: 20px;
}

.expected-results li {
  margin-bottom: 5px;
  color: #333;
}

.log-section {
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.log-section h3 {
  margin: 0;
  padding: 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
  color: #333;
}

.log-controls {
  padding: 10px 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
  display: flex;
  gap: 10px;
}

.log-content {
  height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.log-item {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  font-family: monospace;
}

.log-item.info {
  background: #e6f7ff;
  color: #1890ff;
}

.log-item.success {
  background: #f6ffed;
  color: #52c41a;
}

.log-item.error {
  background: #fff2f0;
  color: #ff4d4f;
}

.log-time {
  color: #999;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

@media (max-width: 768px) {
  .controls {
    flex-direction: column;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .players-grid {
    grid-template-columns: 1fr;
  }
}
</style>
